﻿(function () {
    "use strict";
    var local = WinJS.Application.local;
    var appModel = Windows.ApplicationModel;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var fileName = "favouriteSearches.txt";
    var file;
    var app = WinJS.Application;

    var appData = Windows.Storage.ApplicationData.current;

    WinJS.UI.Pages.define("/pages/home/home.html", {
        init: function (element, options) {
            HomeCodeBehind.callLoadCities();
            HomeCodeBehind.callLoadSectors();
            HomeCodeBehind.callEmploymentTypes();
            WinJS.Binding.processAll(null, ViewModels.searchList);
            local.exists(fileName).then(function () {
                appData.localFolder.createFileAsync(fileName);
            }, function (e) {
                message = new Windows.UI.Popups.MessageDialog("Възникна проблем при обработката на Вашата заявка. Моля опитайте отново!");
                if (e.message != undefined) {
                    console.log(e.message);
                    message.showAsync();
                }
                else if (e.statusText != undefined) {
                    console.log(e.message);
                    message.showAsync();
                }
                else {
                    message.showAsync();
                }
            });

            appData.localFolder.getFileAsync(fileName).then(function (resultFile) {

                file = resultFile;
            }, function (e) {
                message = new Windows.UI.Popups.MessageDialog("Възникна проблем при обработката на Вашата заявка. Моля опитайте отново!");
                if (e.message != undefined) {  // If the URL is really malformed or blank.
                    console.log(e.message);
                    message.showAsync();
                }
                else if (e.statusText != undefined) { // If an XmlHttpRequest is made.
                    console.log(e.message);
                    message.showAsync();
                }
                else {
                    message.showAsync();
                }
            });
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />
            /// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
            /// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />

            var listView = document.getElementById("sectors").winControl;

            if (viewState === Windows.UI.ViewManagement.ApplicationViewState.snapped) {
                if (listView.layout.horizontal) {
                    listView.layout = new WinJS.UI.ListLayout();
                }
            }
            else if (!listView.layout.horizontal) {
                listView.layout = new WinJS.UI.GridLayout();
            }
        },

        ready: function (element, options) {
            var searchButton = document.getElementById("cmdSearch").winControl;
            var selectAllButton = document.getElementById("cmdSelectAll").winControl;
            var clearAllButton = document.getElementById("cmdClearAll").winControl;
            var saveBtn = document.getElementById("cmdSave").winControl;
            var selectedCities = document.getElementById("cities").winControl;
            var selectedSectors = document.getElementById("sectors").winControl;
            var selectedEmploymentOptions = document.getElementById("employmentOptions").winControl;
            var saveFavouritesBtn = document.getElementById("saveFavourtesBtn");
            var loadBtn = document.getElementById("cmdLoad");
            var favName = document.getElementById("searchName");
            var favDescription = document.getElementById("searchDescription");
            var faq = document.getElementById("faq");

            WinJS.Utilities.id("cmdLoadFile").listen("click", function () {

                var openPicker = Windows.Storage.Pickers.FileOpenPicker();
                openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;

                openPicker.fileTypeFilter.append(".txt");
                openPicker.pickSingleFileAsync().then(function (file) {

                    if (file) {
                        Windows.Storage.FileIO.readTextAsync(file, Windows.Storage.Streams.UnicodeEncoding.utf8).done(function (text) {
                            Data.saveText(text);
                            WinJS.Navigation.navigate("/pages/loaded/loadedInfo.html");
                        });
                    }
                });
            });

            loadBtn.addEventListener("click", function () {

                Windows.Storage.FileIO.readTextAsync(file).done(function (text) {

                    var results = [];

                    var entries = text.split(";");

                    for (var i = 0; i < entries.length - 1; i++) {
                        results.push(JSON.parse(entries[i]));
                    }

                    ViewModels.createSearchList(results);

                    var loadFlyout = document.getElementById("loadFlyout").winControl;
                    loadFlyout.show();
                });
            });

            saveFavouritesBtn.addEventListener("click", function () {

                HomeCodeBehind.createQueryString().then(function (dataString) {

                    var data = {
                        name: favName.value,
                        description: favDescription.value,
                        searchString: dataString
                    }

                    var dataAsText = JSON.stringify(data) + ";";

                    Windows.Storage.FileIO.appendTextAsync(file, dataAsText).done(function () {
                        favName.innerText = "";
                        favDescription.innerText = "";
                    }, function (err) {
                        favName.innerText = "";
                        favDescription.innerText = "";
                        console.log(err);
                    });
                }, function (e) {
                    message = new Windows.UI.Popups.MessageDialog("Възникна проблем при обработката на Вашата заявка. Моля опитайте отново!");
                    if (e.message != undefined) {  // If the URL is really malformed or blank.
                        console.log(e.message);
                        message.showAsync();
                    }
                    else if (e.statusText != undefined) { // If an XmlHttpRequest is made.
                        console.log(e.message);
                        message.showAsync();
                    }
                    else {
                        message.showAsync();
                    }
                });
            });

            clearAllButton.addEventListener("click", function () {

                selectedCities.selection.clear();
                selectedSectors.selection.clear();
                selectedEmploymentOptions.selection.clear();
            });

            selectAllButton.addEventListener("click", function () {

                selectedSectors.selection.selectAll();
                selectedEmploymentOptions.selection.selectAll();
            });

            searchButton.addEventListener("click", function () {

                HomeCodeBehind.createQueryString().then(function (query) {
                    ResultCodeBehind.callLoadJobOffers(query);
                });

                nav.navigate("/pages/searchresults/searchresults.html");
            });

            faq.addEventListener("click", function () {

                nav.navigate("/pages/faq/faq.html");
            });

            saveBtn.addEventListener("click", function () {
                var flyOut = document.getElementById("saveFlyout").winControl;
                flyOut.show();
            });
        }
    });

    app.onactivated = function (args) {

        var favName = document.getElementById("searchName");
        var favDescription = document.getElementById("searchDescription");

        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

            } else {
                favName.innerText = WinJS.Application.sessionState["searchName"].value;
                favDescription.innerText = WinJS.Application.sessionState["searchDescription"].value;
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        var favName = document.getElementById("searchName");
        var favDescription = document.getElementById("searchDescription");

        if (favName) {
            WinJS.Application.sessionState["searchName"] = favName.value.toString();
        }

        if (favDescription) {
            WinJS.Application.sessionState["searchDescription"] = favDescription.value.toString();
        }
        app.sessionState.history = nav.history;
    };
})();
